/*pmFWCFu5nhKkBzYmrkBakSAM+Inca+/2SazZgz119uT/d0gZJMONgfRaOvs2SpQg*/
/*
 * @Author: Chendch
 * @Date: 2020-10-13 16:56:24
 * @LastEditors: Chendch
 * @LastEditTime: 2021-06-30 16:15:49
 */
import SyncLoadComp from '../../utils/SyncLoadComp';
import {queryEnvParamUrl} from "./../dataManage/queryEnvUrl";
import {companyDrawUrl, referUrls} from "../CONSTANCE";
import excelImportconfig from 'uap/common/components/excelImportconfig';
import { onMainTableButtonClick, onMainTableOprButtonClick, setMainTablePageButton } from '../events/SupMainTableBtnAction';
import {
  convertForm2GridData, dealRefTemplateItems,querySupplierVersion,
  filterEmptyData, getCurParam, getDialogConfig, hasOperateAuth, resetTableRows, resizeForm,
  setCodeAndDeleteStatusFieldLink, setFinanceAndStockReferCondition, showAddressBookDialog,
  showFormulaSetting, updateFormItemDisable, updateFormItemRequire, validateFormulaSetting
} from '../../utils/SupplierUtils';
import {toast, pageTo} from 'nc-lightapp-front';
let tempData = null;
/**
 * 创建页面参数
 * @param pagecode
 * @param appcode
 * @returns {*}
 */
const createUIDomParam = function(pagecode, appcode){
  var param  = {pagecode:pagecode};
  return window.location.href.startsWith('http://localhost:3006') ? {...param, appcode: appcode} : param;
};

export default function(props) {
  const  _this = this;
  let tempParam = createUIDomParam(this.props.pagecode, pageTo.getAppCode());
  props.createUIDom(tempParam,(data)=>{
    tempData = data;
    SyncLoadComp.call(this,{
      props:this.props,
      urlsArr:Object.values(referUrls),
      success:()=>{afterInitLoad.call(_this)},
      fail:()=>{afterInitLoad.call(_this)}
    })
  });
}

async function afterInitLoad() {
  const param = await queryEnvParamUrl.call(this);
  if(param == "error") return ;
  //获得个性化参数
  this.state.envParam = getInitEnvParamObj.call(this, tempData.context,param.org);
  //个性化设置的org
  this.state.indivOrg = tempData.context;
  this.state.busiPortraitUrl = companyDrawUrl || param.busiPortraitUrl;
  resetStateAfterLoadLang.call(this, modiferMeta)
}

function getInitEnvParamObj(context,param){
  //是业务单元节点:走个性化，不是业务单元节点：走初始化的参数
  return this.props.nodeType == 'ORG_NODE'?context:{
      pk_org:param.pk_org,
      pk_group:param.pk_group,
      org_Name:param.name
  };
}

function modiferMeta(callback) {
  this.props.meta.setMeta(tempData.template,()=>{
    //处理元数据
    dealMetaItems.call(this, tempData.template);
    //设置查询区默认值
    this.setSearchAreaOrgDefaultValue();
    //使用NCTable,适配模板
    this.meta2TableFieldAdapter('custsupbankacc');
  });

  //初始页面 设置按钮状态
  debugger
  this.props.button.setButtons(tempData.button || [],()=>{
    let excelimportconfig = excelImportconfig(this.props,'uapbd',this.props.billType,true,'',{'appcode':pageTo.getAppCode() , 'pagecode':this.props.importTemplate},()=>{
        this.onSearch({isClickSearch:false,isRefreshList:false,checagepage:true},this.setTableData);
    });
    this.props.button.setUploadConfig("Import",excelimportconfig);
    let billtype = 'supplieraddress';
    let fitype = 'supplierfi';
    let stocktype = 'supplierstock';
    let supbanktype = "supbankacc";

    if('10140SUG' === this.props.appcode){
        billtype = 'supplieraddress';
        fitype = 'supplierfi';
        stocktype = 'supplierstock';
        supbanktype = `${supbanktype}_grp`;

    }else if('10140SUO' === this.props.appcode){
        billtype = 'supplieraddress_org';
        fitype = 'supplierfi_org';
        stocktype = 'supplierstock_org';
        supbanktype = `${supbanktype}_org`;

    }else if('10140SUB' === this.props.appcode){
        billtype = 'supplieraddress_glb';
        fitype = 'supplierfi_glb';
        stocktype = 'supplierstock_glb';
        supbanktype = `${supbanktype}_glb`;
    }
    let excelimportficonfig = excelImportconfig(this.props,'uapbd',fitype,true,'',{'appcode':this.props.appcode , 'pagecode':this.props.importTemplate},()=>{
        this.onSearch({isClickSearch:false,isRefreshList:false,checagepage:true},this.setTableData);
    });
    this.props.button.setUploadConfig("importsuppfi",excelimportficonfig);
    let excelimportstockconfig = excelImportconfig(this.props,'uapbd',stocktype,true,'',{'appcode':this.props.appcode , 'pagecode':this.props.importTemplate},()=>{
        this.onSearch({isClickSearch:false,isRefreshList:false,checagepage:true},this.setTableData);
    });
    this.props.button.setUploadConfig("importsuppstock",excelimportstockconfig);
    let excelimportaddconfig = excelImportconfig(this.props,'uapbd',billtype,true,'',{'appcode':this.props.appcode , 'pagecode':this.props.importTemplate},()=>{
        this.onSearch({isClickSearch:false,isRefreshList:false,checagepage:true},this.setTableData);
    });
    this.props.button.setUploadConfig("importsuppadd",excelimportaddconfig);

    let excelimportsupbank = excelImportconfig(this.props,'uapbd',supbanktype,true,'',{'appcode':this.props.appcode , 'pagecode':this.props.importTemplate},()=>{
        this.onSearch({isClickSearch:false,isRefreshList:false,checagepage:true},this.setTableData);
    });
    this.props.button.setUploadConfig("SupBankAcc_Import",excelimportsupbank);

    setMainTablePageButton.call(this,true);
  })
}

/**
* 处理元数据项
  * @param meta
*/
function dealMetaItems(meta) {
    let _props = this.props;
  //联系人组织权限删除操作
  meta["SubjectOrg"].items.push({
      attrcode: 'opr',
      label: this.Lang['dataTemplet-000002'],
      width: 200,
      fixed: 'right',
      className: 'table-opr',
      itemtype: 'customer',
      visible: true,
      render: (text, record, index) => {
        return <a onClick={()=>this.deletePromptBox(record.pk_org.value)}>{this.Lang['10140SUG-000071']}</a>
      }
  })
    //版本化 版本号添加超链接
    meta['versionList'].items = meta['versionList'].items.map((item) => {
        if (item.attrcode === 'version') {
            item.itemtype = 'customer';
            item.render = (text, record) => {
                return (
                    <span
                        style={{ color: '#007ace', cursor: 'pointer' }}
                        onClick={() => {
                            this.props.modal.show('versionCardmodal')
                            querySupplierVersion(record,'',_props);
                        }}
                    >
                        {record && record['values'] && record['values']['version'] && record['values']['version'].value}
                    </span>
                );
            };
        }
        return item;
    });
  const addOperateField = (meta) =>{
      meta['supplier_baseInfo'].items.push(this.state.table.mainTable.operator);//基本信息列表操作列
  };
  dealRefTemplateItems.call(this,meta);//处理参照
  setCodeAndDeleteStatusFieldLink.call(this,meta);//设置编码和删除状态链接
  addOperateField(meta);//添加操作列
  //设置供应商银行账户 基本信息和网银信息的formrelation关系
  meta.formrelation = new Object();
  meta.formrelation['accbasinfo'] = ['netbankinfo'];
  this.setOrgAssignToCache();
};

function resetStateAfterLoadLang(callback) {
  this.state = Object.assign({
    forceRender: true,
    selectType: 'onlyChild',
    leftTree:[],
    rightTree:[],
    pageInfo:null,//记录列表分页信息
    loadLang:true,//加载多语
    envParam:undefined,//初始参数
    openDialog:false,
    openDeleteDialog:false,
    batchUpdateStepClick:false,//向导批改参数
    assignStepClick:false,//向导分配参数
    loadSupBank:false,//加载银行账户组件
    queryInfo:{logic:"and",conditions:[]},//缓存的查询条件
    newQueryInfo:{logic:"and",conditions:[]},
    relateQueryId:null,
    allpks:[],
    busiPortraitUrl:null,//企业画像url
    orgAssignCacheField:{},
    supplierMain:{code:'',name:''},
    selectedRecords:undefined,//列表到卡片所有操作都依赖该对象属性
    dirtyRecords:undefined,//列表到卡片操作辅助属性（在selectedRecords失效时，用这个）
    dblClkRecord:undefined,//卡片 两个关联关系的子表编辑时需要这个对象属性
    queryRecords:[],//表格数据
    status:'browse',
    otherParam:undefined,//其他参数（如在userjson中传递的参数）
    //冻结时业务单元参照的参数
    freezeOrgParam:{
        onChange:this.onBusinessUnitChange.bind(this),
        value:null,
        isMultiSelectedEnabled:true,
        fieldid:'businessunittreeref',
        popWindowClassName:'businessunit-zindex',
        isShowUnit:false,
        queryCondition:{
            TreeRefActionExt:'nccloud.web.uapbd.supplier.suprefcondition.action.FreezeBusinessUnitRefSqlBuilder'
        }
    },
    //列表
    table:{
        //显示停用配置
        showOff:{
            checked: undefined,
            disabled: false,
            onChange: (val) => {
                this.state.table.showOff.checked = val;
                this.setState(this.state, () => {
                    this.onSearch({checagepage:true},this.setTableData);
                });
            },
            name: this.Lang['10140SUG-000114']/* 国际化处理： 显示停用*/
        },
        //主页面按钮配置
        buttonConfig: {
            area: 'supplier_baseInfo',
            buttonLimit: 3,
            onButtonClick: this.onMainTableButtonClick,
        },
        //主页面查询区配置
        search: {
            id: 'supplierquery',
            clickSearchBtn: () => {
                this.onSearch({isClickSearch:true,isRefreshList:false},this.setTableData);
            },
            clickAdvBtnEve:()=>{this.setSearchAreaOrgDefaultValue()},
            url:'/nccloud/uapbd/supplier/querySupplierBaseInfo.do'
        },
        //主列表配置
        mainTable:{
            id: 'supplier_baseInfo',
            showCheck:true,
            showIndex:true,
            onSelected:this.onMainTableChecked.bind(this,this.disabledApproveButtons),
            onRowClick:this.onMainTableRecordClick,
            onRowDoubleClick:this.onMainTableDoubleClick,
            onSelectedAll:this.onMainTableSelectedAll,
            handlePageInfoChange:this.onMainTablePageInfoClick,
            operator:{
                attrcode: 'opr',
                itemtype:'customer',
                label: this.Lang['10140SUG-000035'],/* 国际化处理： 操作*/
                width: 200,
                className : 'table-opr',
                fixed: 'right',
                visible: true,
                render: (text, record, index) => {
                    let btnKeyArr = new Array();
                    //添加操作列按钮
                    let buttonArray = this.props.button.getButtons().filter(button=>{
                        if( button.area == 'supplier_baseInfo_opr'){return button}
                    })
                    //过滤操作列启用停用按钮
                    for(let button of buttonArray){
                        if(button.key == 'OprEnable'  && record['enablestate'].value == '2'){
                            continue;
                        }else if(button.key == 'OprDisable'  && record['enablestate'].value != '2'){
                            continue;
                        }else if(button.key == 'ApplyQuery' && !record['pk_supplier_pf'].value){
                            continue;
                        // }else if(button.key == 'CreateCust' && !record['iscustomer'].value){
                        //     continue;
                        }else {
                            btnKeyArr.push(button.key)
                        }
                    }
                    let hasAuth = hasOperateAuth.call(this,[record]);
                    return this.props.button.createOprationButton(hasAuth?btnKeyArr:[], {
                        area: 'supplier_baseInfo_opr',
                        buttonLimit: 3,
                        onButtonClick:this.onMainTableOprBtnClick.bind(this,record,index)
                    });
                }
            }
        }
    },
    //弹窗需要的配置
    dialog:{
        linkman:{
            formName:this.Lang['10140SUG-000136'],/* 国际化处理： 联系人*/
            formId:'linkman',
            targetId:'suplinkman',
            assignOrg:this.assignOrg.bind(this),
            refreshOrg:this.refreshOrg.bind(this)
        },
        supbankacc:{
            tableId:'custsupbankacc',
            tableName:this.Lang['10140SUG-000139'],/* 国际化处理： 供应商银行账户*/
            targetId:'supbankacc',
            pk_supplier:null,
        },
        supaddress:{
            tableId:'supaddress',
            tableName:this.Lang['10140SUG-000065'],/* 国际化处理： 供应商发货地址*/
            pk_supplier:null,
        },
        suprename:{
            tableId:'suprename',
            tableName:this.Lang['10140SUG-000234'],/* 国际化处理： 供应商更名记录*/
            pk_supplier:null,
        }
    },
    //打印配置
    printNodeKey:null,
    printUrl:null,
    printPks:null,
  },{envParam:this.state.envParam,indivOrg:this.state.indivOrg,busiPortraitUrl:this.state.busiPortraitUrl});
  this.setState(this.state, () => {
    callback && callback.call(this)
  });
}


/*pmFWCFu5nhKkBzYmrkBakSAM+Inca+/2SazZgz119uT/d0gZJMONgfRaOvs2SpQg*/
